package com.uxhuanche.ui.base;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * @author ketan on 2020/8/22.
 */
public class KKFragmentPagerAdapter extends FragmentStatePagerAdapter {
    private FragmentManager mFm;

    private List<Class<?>> mClasses;
    private int mContainerId;

    public KKFragmentPagerAdapter(@NonNull FragmentManager fm, List<Class<?>> classes) {
        super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        this.mFm = fm;
        this.mClasses = classes;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        this.mContainerId = container.getId();
        return super.instantiateItem(container, position);
    }

    @NonNull
    @Override
    public Fragment getItem(int position) {
        return getFragment(mFm, mClasses.get(position), mContainerId, position);
    }

    @Override
    public int getCount() {
        return mClasses.size();
    }

    public Fragment getFragment(FragmentManager fm, Class<?> cls, int containerId, int pos) {
        Fragment ft = null;
        if (fm != null)
            ft = fm.findFragmentByTag(makeFragmentName(containerId, pos));
        if (ft == null) {
            try {
                ft = (Fragment) cls.getConstructor((Class<?>) null).newInstance((Object) null);
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) {
                e.printStackTrace();
            }
        }
        return ft;
    }

    private String makeFragmentName(int viewId, long id) {
        return "android:switcher:" + viewId + ":" + id;
    }
}
